const cartModel = require('../model/cart/CartModel')

class CartController {
  // 向数据库中添加新的订单
  static async addCart (ctx) {
    let { goods_id, name, drinks, price, count, cate } = ctx.request.body

    const user = ctx.user
    const data = {
      user_id: user.openid,
      goods_id, 
      name, 
      drinks, 
      price, 
      count, 
      cate
    }
    await cartModel.insertMany([data])
    ctx.body = { err: 0, msg: 'success', data: { msg: 'success' } }
  }

  // 该用户的订单
  static async list (ctx) {
    const user = ctx.user
    const params = {
      user_id: user.openid,
    }
    const list = await cartModel.find(params)
    ctx.body = { err: 0, msg: 'success', data: { list } }
  }

  // 清除购物车
  static async clear (ctx) {
    const user = ctx.user
    const params = {
      user_id: user.openid,
    }
    await cartModel.deleteMany(params)
    ctx.body = { err: 0, msg: 'success', data: { msg: 'success' } }
  }

   // 清除单件商品
   static async sub (ctx) {
    const { goods_id, flag, count } = ctx.request.query
    const user = ctx.user
    const params = {
      user_id: user.openid,
      goods_id
    }
    if (flag == 'del') {
      await cartModel.deleteOne(params)
    } else {
      await cartModel.updateOne(params, { $set: { count: parseInt(count) - 1 } })
    }
    ctx.body = { err: 0, msg: 'success', data: { msg: 'success' } }
  }

  // 添加单件商品数量
  static async single (ctx) {
    const { goods_id, count } = ctx.request.query
    const user = ctx.user
    const params = {
      user_id: user.openid,
      goods_id,
    }
    await cartModel.updateOne(params, { $set: { count: parseInt(count) + 1 } })
    ctx.body = { err: 0, msg: 'success', data: { msg: 'success' } }
  }
}

module.exports = CartController